<template>
    <div id="login-page">
        <div class="top-part">
            <div class="header-container">
                <div class="info-top">简云社</div>
                <div class="info-bottom">有问题就会有答案</div>
            </div>
        </div>
        <div class="center-part">
            <div class="login-container">
                <div class="left-part">
                    <img src="https://cdn.pixabay.com/photo/2023/11/07/18/57/robin-8373155_640.jpg" alt="" width="100%"
                        height="100%">
                </div>
                <div class="right-part">
                    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                        <el-tab-pane label="验证码登录" name="first">
                            <el-form ref="ruleFormRef1" style="max-width: 600px" :model="ruleForm1" status-icon
                                :rules="rules1" label-width="auto" class="demo-ruleForm1">
                                <el-form-item label="" prop="phone">
                                    <el-input v-model="ruleForm1.phone" style="max-width: 600px" placeholder="手机号">
                                        <template #prepend>中国 +86
                                            <el-divider direction="vertical" />
                                        </template>
                                    </el-input>
                                </el-form-item>

                                <el-form-item label="" prop="code">
                                    <el-input v-model="ruleForm1.code" style="max-width: 600px;"
                                        placeholder="输入 6 位短信验证码">
                                        <template #append>
                                            <span v-show="!sendCodeFlag" class="code-button" @click="handleSendCode">
                                                获取短信验证码
                                            </span>
                                            <span v-show="sendCodeFlag" style="margin-left: 5px;">已发送，{{ count }}
                                                秒后重试</span>
                                        </template>
                                    </el-input>
                                </el-form-item>
                            </el-form>
                            <el-button class="login-btn" type="primary" :element-loading-text="loadingText"
                                v-loading.fullscreen.lock="fullscreenLoading" @click="submitForm1(ruleFormRef1)">
                                登录/注册
                            </el-button>
                        </el-tab-pane>


                        <el-tab-pane label="密码登录" name="second">
                            <el-form ref="ruleFormRef2" style="max-width: 600px" :model="ruleForm2" status-icon
                                :rules="rules2" label-width="auto" class="demo-ruleForm">
                                <el-form-item label="" prop="oAthId">
                                    <el-input v-model="ruleForm2.oAthId" autocomplete="off" placeholder="账号（手机号/邮箱）" />
                                </el-form-item>
                                <el-form-item label="" prop="password">
                                    <el-input v-model="ruleForm2.password" type="password" autocomplete="off"
                                        show-password placeholder="密码（至少6位）" />
                                </el-form-item>
                            </el-form>
                            <div class="forget-password">
                                <span>忘记密码</span>
                            </div>
                            <el-button class="login-btn" type="primary" :element-loading-text="loadingText"
                                v-loading.fullscreen.lock="fullscreenLoading"
                                @click="submitForm2(ruleFormRef2)">登录</el-button>
                        </el-tab-pane>
                    </el-tabs>
                    <div class="tips">注意：未注册的手机号验证后自动注册并登录，注册即代表同意《云社协议》《隐私保护指引》</div>
                </div>
            </div>
        </div>
        <div class="bottom-part"></div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { TabsPaneContext, FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { login, sendCode } from '@/api/login'
import store from '@/store'
const router = useRouter()
//页面加载动画
const fullscreenLoading = ref(false)
//页面加载文字
const loadingText = ref('登录中...')
//默认选密码登录
const activeName = ref('first')
//切换登录方式
const handleClick = (tab: TabsPaneContext, event: Event) => {
    console.log(tab, event)
}

//验证码登录================================================================================================================
const ruleFormRef1 = ref<FormInstance>()
const ruleForm1 = reactive({
    phone: '',
    code: '',
})
const sendCodeFlag = ref(false)
const count = ref(60)

//校检手机号
const valiPhone = (rule: any, value: string, callback: any) => {
    const reg = /^1[3456789]\d{9}$/
    if (!value) {
        return callback(new Error('请输入手机号！'))
    } else if (!reg.test(value)) {
        return callback(new Error('请输入正确的手机号！'))
    } else {
        callback()
    }
}

const rules1 = reactive<FormRules<typeof ruleForm1>>({
    phone: [
        { validator: valiPhone, trigger: 'blur', required: true },
        { min: 6, message: '账号长度不能小于6位', trigger: 'blur' }
    ],
    code: [
        { message: '请输入验证码！', trigger: 'blur', required: true },
        { min: 6, max: 6, message: '请输入 6 位短信验证码', trigger: 'blur' }
    ],
})


//提交验证码登录表单
const submitForm1 = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            fullscreenLoading.value = true
            login({
                phone: ruleForm1.phone,
                code: ruleForm1.code
            }).then(res => {
                if (res?.flag) {
                    //记录令牌信息
                    store.commit('setToken', res.data)
                    //跳转首页
                    setTimeout(() => {
                        fullscreenLoading.value = false
                        router.push('/home')
                    }, 1000)
                } else {
                    fullscreenLoading.value = false
                    ElMessage.error(res.message)
                }
            }).catch(err => {
                fullscreenLoading.value = false
                ElMessage.error(err.message)
            })
        }
    })
}


//发送验证码
const handleSendCode = () => {
    if (ruleForm1.phone == '') {
        ElMessage.error('请输入手机号！')
        return
    }
    const reg = /^1[3456789]\d{9}$/
    if (!reg.test(ruleForm1.phone)) {
        ElMessage.error('请输入正确的手机号！')
        return
    }
    sendCode(ruleForm1.phone).then(res => {
        if (res.flag) {
            ElMessage.success('发送成功！')
            sendCodeFlag.value = true
            var timer = setInterval(() => {
                if (count.value > 0) {
                    count.value--;
                } else {
                    sendCodeFlag.value = false;
                    clearInterval(timer)
                    count.value = 60
                }
            }, 1000)
        } else {
            ElMessage.error(res.msg)
        }
    }).catch(err => {
        ElMessage.error(err.message)
    })
}



//密码登录==================================================================================================================
const ruleFormRef2 = ref<FormInstance>()
const ruleForm2 = reactive({
    oAthId: '',
    password: '',
})

//校验规则
const rules2 = reactive<FormRules<typeof ruleForm2>>({
    oAthId: [{ message: "请输入账号（手机号/邮箱）！", trigger: 'blur', required: true },
    { min: 6, message: '账号长度不能小于6位', trigger: 'blur' }
    ],
    password: [{ message: '请输入密码！', trigger: 'blur', required: true },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
    ],
})

//判断是账号是手机还是邮箱,还是账号
const idtype = (val: string) => {
    const reg = /^1[3456789]\d{9}$/
    const reg2 = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
    if (reg.test(val)) {
        return 'phone'
    } else if (reg2.test(val)) {
        return 'email'
    }
    return 'username'
}


// 提交密码登录表单
const submitForm2 = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            fullscreenLoading.value = true
            //获取登录类型
            var loginType = idtype(ruleForm2.oAthId)
            const loginIfo = {
                [loginType]: ruleForm2.oAthId,
                password: ruleForm2.password
            }
            login(loginIfo).then(res => {
                if (res?.flag) {
                    //记录令牌信息
                    store.commit('setToken', res.data)
                    setTimeout(() => {
                        fullscreenLoading.value = false
                        router.push('/home')
                    }, 1000)
                } else {
                    fullscreenLoading.value = false
                    ElMessage.error(res.message)
                }
            }).catch(err => {
                fullscreenLoading.value = false
                ElMessage.error(err.message)
            })
        }
    })
}
</script>

<style lang="scss" scoped src="./style.css"></style>